﻿using System;
using System.Collections.Generic;
using SuperX.Common;
using SuperX.Common.APIManager;
using SuperX.Common.Log;
using SuperX.Common.Respository;

namespace SuperX.PermissionsService
{
    public class PermissionsServer : HostService
    {
        public override string ServiceType { get; set; }

        public PermissionsConfig Config { get; set; }

        private PermissionsController LoginWebApi;

        private DynamicApiController Controller;

        public override bool Exit()
        {
            return true;
        }

        public override bool Init()
        {
            Controller = new PermissionsController(this);
            return true;
        }

        public override bool Load(string fileName)
        {
            FileName = fileName;
            Repository = new JsonRepository(FileName);
            Repository.Load(typeof(PermissionsConfig));
            Config = Repository.Model as PermissionsConfig;
            if (Config == null)
            {
                CreateCfgFile();
            }
            return true;
        }

        public override bool SaveAs(string fileName)
        {
            Repository = new JsonRepository(fileName) { Model = Config };
            Repository.Save();
            return true;
        }

        public override bool Start()
        {
            Logger.Info($"{this.GetType().Name}启动");
            return true;
        }

        public override bool Stop()
        {
            Controller = null;
            return true;
        }

        private void CreateCfgFile()
        {
            PermissionsConfig config = new PermissionsConfig();
            config.Users.Add(new User { Id = 1, Name = "iot", Password = Helper.Encryption.Encode("iot") });
            Config = config;
            SaveAs(FullFileName);
        }
    }
}